<template>
  <div class="analytics-container">
    <h1 class="text-center mb-4">数据分析仪表板</h1>
    
    <div class="row mb-4">
      <div class="col-md-6">
        <div class="card">
          <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0">任务性能指标</h5>
            <div class="btn-group">
              <button class="btn btn-sm btn-outline-primary" @click="loadTaskPerformance(7)">7天</button>
              <button class="btn btn-sm btn-outline-primary" @click="loadTaskPerformance(30)">30天</button>
              <button class="btn btn-sm btn-outline-primary" @click="loadTaskPerformance(90)">90天</button>
            </div>
          </div>
          <div class="card-body">
            <div v-if="loading.taskPerformance" class="text-center">
              <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">加载中...</span>
              </div>
            </div>
            <div v-else-if="error.taskPerformance" class="alert alert-danger">
              {{ error.taskPerformance }}
            </div>
            <div v-else>
              <table class="table table-striped">
                <thead>
                  <tr>
                    <th>状态</th>
                    <th>任务数量</th>
                    <th>平均完成时间</th>
                    <th>中位完成时间</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="metric in taskPerformance" :key="metric.status">
                    <td>{{ getStatusText(metric.status) }}</td>
                    <td>{{ metric.task_count }}</td>
                    <td>{{ formatDuration(metric.avg_completion_time_seconds) }}</td>
                    <td>{{ formatDuration(metric.median_completion_time_seconds) }}</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
      
      <div class="col-md-6">
        <div class="card">
          <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0">ClickHouse 统计数据</h5>
            <button class="btn btn-sm btn-primary" @click="triggerSync">
              <i class="bi bi-arrow-repeat"></i> 同步数据
            </button>
          </div>
          <div class="card-body">
            <div v-if="loading.clickhouseStats" class="text-center">
              <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">加载中...</span>
              </div>
            </div>
            <div v-else-if="error.clickhouseStats" class="alert alert-danger">
              {{ error.clickhouseStats }}
            </div>
            <div v-else>
              <h6>状态分布</h6>
              <table class="table table-sm">
                <thead>
                  <tr>
                    <th>状态</th>
                    <th>数量</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="item in clickhouseStats.status_distribution" :key="item.status">
                    <td>{{ getStatusText(item.status) }}</td>
                    <td>{{ item.count }}</td>
                  </tr>
                </tbody>
              </table>
              
              <h6 class="mt-3">平均完成时间</h6>
              <p>{{ formatDuration(clickhouseStats.avg_completion_time_minutes * 60) }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="row">
      <div class="col-12">
        <div class="card">
          <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0">综合分析</h5>
            <div>
              <button class="btn btn-sm btn-outline-success me-2" @click="generateReport('json')">
                导出 JSON
              </button>
              <button class="btn btn-sm btn-outline-success" @click="generateReport('csv')">
                导出 Excel
              </button>
            </div>
          </div>
          <div class="card-body">
            <div v-if="loading.combinedAnalytics" class="text-center">
              <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">加载中...</span>
              </div>
            </div>
            <div v-else-if="error.combinedAnalytics" class="alert alert-danger">
              {{ error.combinedAnalytics }}
            </div>
            <div v-else>
              <div class="row">
                <div class="col-md-6">
                  <h6>用户参与度 (前5名)</h6>
                  <table class="table table-sm">
                    <thead>
                      <tr>
                        <th>用户ID</th>
                        <th>任务数量</th>
                        <th>活跃天数</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr v-for="(user, index) in combinedAnalytics.user_engagement.slice(0, 5)" :key="index">
                        <td>{{ user.user_id }}</td>
                        <td>{{ user.task_count }}</td>
                        <td>{{ user.active_days }}</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
                
                <div class="col-md-6">
                  <h6>状态转换分析</h6>
                  <table class="table table-sm">
                    <thead>
                      <tr>
                        <th>状态</th>
                        <th>数量</th>
                        <th>平均小时</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr v-for="item in combinedAnalytics.status_transition" :key="item.status">
                        <td>{{ getStatusText(item.status) }}</td>
                        <td>{{ item.count }}</td>
                        <td>{{ item.avg_hours_to_status.toFixed(1) }}</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { analyticsApi } from '../api/analytics'

export default {
  name: 'AnalyticsView',
  setup() {
    const taskPerformance = ref([])
    const clickhouseStats = ref({
      status_distribution: [],
      daily_creation: [],
      avg_completion_time_minutes: 0
    })
    const combinedAnalytics = ref({
      performance_metrics: [],
      user_engagement: [],
      status_transition: []
    })
    
    const loading = ref({
      taskPerformance: false,
      clickhouseStats: false,
      combinedAnalytics: false
    })
    
    const error = ref({
      taskPerformance: null,
      clickhouseStats: null,
      combinedAnalytics: null
    })
    
    const loadTaskPerformance = async (days = 30) => {
      loading.value.taskPerformance = true
      error.value.taskPerformance = null
      
      try {
        const response = await analyticsApi.getTaskPerformance(days)
        taskPerformance.value = response.data
      } catch (err) {
        error.value.taskPerformance = '加载任务性能指标失败'
        console.error(err)
      } finally {
        loading.value.taskPerformance = false
      }
    }
    
    const loadClickhouseStats = async () => {
      loading.value.clickhouseStats = true
      error.value.clickhouseStats = null
      
      try {
        const response = await analyticsApi.getClickhouseStats()
        clickhouseStats.value = response.data
      } catch (err) {
        error.value.clickhouseStats = '加载 ClickHouse 统计数据失败'
        console.error(err)
      } finally {
        loading.value.clickhouseStats = false
      }
    }
    
    const loadCombinedAnalytics = async () => {
      loading.value.combinedAnalytics = true
      error.value.combinedAnalytics = null
      
      try {
        const response = await analyticsApi.getCombinedAnalytics()
        combinedAnalytics.value = response.data
      } catch (err) {
        error.value.combinedAnalytics = '加载综合分析数据失败'
        console.error(err)
      } finally {
        loading.value.combinedAnalytics = false
      }
    }
    
    const triggerSync = async () => {
      try {
        await analyticsApi.triggerSync()
        // 重新加载数据
        loadClickhouseStats()
      } catch (err) {
        console.error('触发同步失败', err)
      }
    }
    
    const generateReport = async (format) => {
      try {
        if (format === 'csv') {
          // 对于 CSV 格式，我们需要下载文件
          window.open(`http://localhost:8000/api/v1/analytics/report?format=csv`, '_blank')
        } else {
          // 对于 JSON 格式，我们可以直接在浏览器中查看
          const response = await analyticsApi.generateReport(30, 'json')
          console.log('报告数据:', response.data)
          alert('报告已生成，请查看控制台')
        }
      } catch (err) {
        console.error('生成报告失败', err)
      }
    }
    
    const getStatusText = (status) => {
      const statusMap = {
        'pending': '待处理',
        'in_progress': '进行中',
        'completed': '已完成',
        'failed': '失败'
      }
      return statusMap[status] || status
    }
    
    const formatDuration = (seconds) => {
      if (!seconds) return '0秒'
      
      const hours = Math.floor(seconds / 3600)
      const minutes = Math.floor((seconds % 3600) / 60)
      const remainingSeconds = Math.floor(seconds % 60)
      
      let result = ''
      if (hours > 0) result += `${hours}小时 `
      if (minutes > 0) result += `${minutes}分钟 `
      if (remainingSeconds > 0 || result === '') result += `${remainingSeconds}秒`
      
      return result.trim()
    }
    
    onMounted(() => {
      loadTaskPerformance()
      loadClickhouseStats()
      loadCombinedAnalytics()
    })
    
    return {
      taskPerformance,
      clickhouseStats,
      combinedAnalytics,
      loading,
      error,
      loadTaskPerformance,
      triggerSync,
      generateReport,
      getStatusText,
      formatDuration
    }
  }
}
</script>

<style scoped>
.analytics-container {
  padding: 20px;
}

.card {
  margin-bottom: 20px;
  box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
}

.card-header {
  background-color: #f8f9fa;
  border-bottom: 1px solid rgba(0, 0, 0, 0.125);
}

.text-center {
  text-align: center;
}
</style>
